package com.twang.stock.controller.common;

import com.twang.stock.dto.EbayRequest;
import com.twang.stock.ebay.EbayService;
import com.twang.stock.feign.EbayApiClient;
import com.twang.stock.service.jinyan.CommonService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.nio.file.Files.*;

@RestController
@RequestMapping(value = "/ebay")
@Slf4j
public class EbayController {

    @Autowired
    private EbayService ebayService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private EbayApiClient ebayApiClient;
    @RequestMapping(value = "/")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("nameList", ebayService.getList());
        modelAndView.setViewName("ebay/index");
        return modelAndView;
    }

    @RequestMapping(value = "/detail")
    @ResponseBody
    public ModelAndView detail(String name) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("detailList", ebayService.getDetailList(name));
        modelAndView.setViewName("ebay/goodDetail");
        return modelAndView;
    }


    @RequestMapping(value = "/submit")
    @ResponseBody
    public ModelAndView submit() {
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("ebay/index");
        return modelAndView;
    }

    @RequestMapping(value = "/ebayApi")
    @ResponseBody
    public ModelAndView ebayApi(EbayRequest ebayRequest) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("nameList", ebayService.getList());
        modelAndView.setViewName("ebay/ebayApi");
        return modelAndView;
    }





    @RequestMapping(value = "/ebaySearchByTypeService")
    @ResponseBody
    public void ebaySearchByTypeService(EbayRequest ebayRequest) {
        try {
            String totalPage = commonService.getBaseCommon("ebay_total_page").getCommonValue();
            ebayService.getGoodDetailFeedback(ebayRequest.getGoodsUrl(), Integer.valueOf(totalPage), ebayRequest.getName());
//            int totalpage=Integer.valueOf(totalPage);
//            for(int i=1;i<=totalpage;i++){
//                ebayApiClient.getByPage(ebayRequest.getName(),i);
//            }

        } catch (Exception e) {
            log.error("ebaySearchByTypeService.count exception={}", e);
        }
    }

    // 文件上传接口
//    @RequestMapping("/upload")
//    public ResponseEntity<?> handleFileUpload( @RequestParam("file") MultipartFile file,@RequestParam("username") String uploaderName) {
//
//        if (file.isEmpty()) {
//            return ResponseEntity.badRequest().body("请选择要上传的文件");
//        }
//
//        try {
//            // 使用Paths.get创建临时文件路径
//            Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
//            Path tempFile = Files.createTempFile(tempDir, "upload-", ".tmp");
//
//            // 转换MultipartFile到Java 8兼容写法
//            file.transferTo(tempFile.toFile());
//
//            // 使用Java 8方式读取文件内容
//            String content = readFileContent(tempFile);
//            ebayService.getUserLocationAndFeedback(content,uploaderName);
//            // ...后续解析逻辑不变...
//        } catch (Exception e) {
//            // 异常处理
//            log.error("error --->",e);
//            return ResponseEntity.badRequest().body("处理失败");
//        }
//        return ResponseEntity.ok("处理成功");
//    }

    @RequestMapping("/upload")
    public ResponseEntity<?> handleFileUpload(
            @RequestParam("files") MultipartFile[] files,      // 接收文件数组
            @RequestParam("username") String uploaderName      // 接收用户名
    ) {

        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;

        if (files == null || files.length == 0) {
            return ResponseEntity.badRequest().body("未选择任何文件");
        }

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                errorMessages.add("文件不能为空");
                continue;
            }

            try {
                // 创建临时文件
                Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
                Path tempFile = Files.createTempFile(tempDir, "upload-", ".tmp");

                // 转移文件到临时目录
                file.transferTo(tempFile.toFile());

                // 读取文件内容（示例方法，需根据实际需求实现）
                String content = readFileContent(tempFile);

                // 业务处理（示例服务调用）
                ebayService.getUserLocationAndFeedback(content, uploaderName);

                successCount++;
            } catch (Exception e) {
                errorMessages.add("处理文件失败: " + file.getOriginalFilename() + " - " + e.getMessage());
            }
        }

        if (!errorMessages.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(String.format("上传失败 %d/%d 个文件，错误详情：%s",
                            errorMessages.size(), files.length, String.join(", ", errorMessages)));
        }

        return ResponseEntity.ok(new UploadResult(
                files.length,       // 总文件数
                successCount,      // 成功数
                errorMessages       // 错误列表
        ));
    }
    @RequestMapping(value = "/ebayApiSearch")
    @ResponseBody
    public ResponseEntity<?> ebayApiSearch(@RequestParam("files") MultipartFile[] files, @RequestParam("username") String uploaderName) {
        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;

        if (files == null || files.length == 0) {
            return ResponseEntity.badRequest().body("未选择任何文件");
        }

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                errorMessages.add("文件不能为空");
                continue;
            }

            try {
                // 创建临时文件
                Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
                Path tempFile = Files.createTempFile(tempDir, "upload-", ".tmp");

                // 转移文件到临时目录
                file.transferTo(tempFile.toFile());

                // 读取文件内容（示例方法，需根据实际需求实现）
                String content = readFileContent(tempFile);

                // 业务处理（示例服务调用）
                //ebayService.getUserLocationAndFeedback(content, uploaderName);
             //   ebayApiClient.processResponseMessage(content,uploaderName);
                successCount++;
            } catch (Exception e) {
                errorMessages.add("处理文件失败: " + file.getOriginalFilename() + " - " + e.getMessage());
            }
        }

        String totalPage = commonService.getBaseCommon("ebay_total_page").getCommonValue();
        int totalpage=Integer.valueOf(totalPage);
        try {
            for(int i=1;i<=50;i++){
               ebayApiClient.getByPage(uploaderName,i);
            }
        } catch (Exception e) {
            log.error("ebaySearchByTypeService.count exception={}", e);
        }

        if (!errorMessages.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(String.format("上传失败 %d/%d 个文件，错误详情：%s",
                            errorMessages.size(), files.length, String.join(", ", errorMessages)));
        }
        return ResponseEntity.ok(new UploadResult( files.length, successCount, errorMessages));
    }



    // 新增结果类定义
    @Data
    @AllArgsConstructor
    class UploadResult {
        private final int total;          // 总文件数
        private final int success;       // 成功数
        private final List<String> errors; // 错误详情
    }

    // Java 8兼容的文件读取方法
    private String readFileContent(Path filePath) throws IOException {
        return new String(
                Files.readAllBytes(filePath),
                StandardCharsets.UTF_8
        );
    }

}
